<template>
  <div class="cart-container">
    <a-card class="cart-card" :bordered="false">
      <!-- 购物车标题 -->
      <div class="cart-header">
        <h2 class="text-xl font-semibold">我的购物车</h2>
        <span class="text-gray-500">共 {{ totalItems }} 件商品</span>
      </div>

      <!-- 购物车内容 -->
      <template v-if="storeGroups.length > 0">
        <!-- 商店分组列表 -->
        <div class="store-groups">
          <a-card
            v-for="store in storeGroups"
            :key="store.storeId"
            class="store-group-card mb-4"
            :bordered="false"
          >
            <!-- 商店信息头部 -->
            <div class="store-header">
              <div class="store-info">
                <a-checkbox
                  :checked="isStoreSelected(store.storeId)"
                  @change="
                    (e) => toggleStoreSelection(store.storeId, e.target.checked)
                  "
                >
                  <div class="flex items-center gap-2">
                    <shop-outlined class="text-primary" />
                    <span class="store-name">{{ store.storeName }}</span>
                  </div>
                </a-checkbox>
              </div>
            </div>

            <!-- 商品列表 -->
            <div class="cart-items">
              <transition-group name="list">
                <div
                  v-for="item in store.cartItems"
                  :key="item.id"
                  class="cart-item group"
                >
                  <!-- 商品选择框 -->
                  <a-checkbox
                    :checked="item.selected === 1"
                    @change="(e) => handleItemSelection(item, e.target.checked)"
                  />

                  <!-- 商品信息 -->
                  <div class="item-info">
                    <div class="item-image-container">
                      <a-image
                        :src="item.productImage"
                        :alt="item.productName"
                        :fallback="defaultImage"
                        class="item-image"
                      />
                    </div>

                    <div class="item-details">
                      <div class="item-name">{{ item.productName }}</div>
                      <div class="item-specs">
                        <a-tag color="default">{{ item.size }}</a-tag>
                      </div>
                      <div class="item-price">
                        <span class="currency">¥</span>
                        <span class="amount">{{
                          formatPrice(item.price)
                        }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- 商品操作区 -->
                  <div class="item-actions">
                    <div class="quantity-control">
                      <a-input-number
                        v-model:value="item.quantity"
                        :min="1"
                        :max="99"
                        size="small"
                        @change="(value) => handleQuantityChange(item, value)"
                      />
                    </div>

                    <div class="item-subtotal">
                      <span class="currency">¥</span>
                      <span class="amount">{{
                        formatPrice(item.totalPrice)
                      }}</span>
                    </div>

                    <a-button
                      type="text"
                      danger
                      class="delete-btn opacity-0 group-hover:opacity-100"
                      @click="confirmDelete(item)"
                    >
                      <delete-outlined />
                    </a-button>
                  </div>
                </div>
              </transition-group>
            </div>

            <!-- 商店结算栏 -->
            <div class="store-footer">
              <div class="selected-info">
                已选择 {{ getStoreSelectedCount(store) }} 件商品
              </div>
              <div class="checkout-area">
                <div class="subtotal">
                  <span>商品小计：</span>
                  <span class="currency">¥</span>
                  <span class="amount">{{
                    formatPrice(calculateStoreTotal(store))
                  }}</span>
                </div>
                <a-button
                  type="primary"
                  size="large"
                  :disabled="!hasStoreSelectedItems(store)"
                  @click="handleCheckout(store)"
                >
                  结算
                </a-button>
              </div>
            </div>
          </a-card>
        </div>

        <!-- 底部汇总信息 -->
        <div class="cart-summary">
          <div class="summary-info">
            <span>已选择 {{ totalSelectedItems }} 件商品</span>
            <span class="mx-4">|</span>
            <span>总计：</span>
            <span class="total-price">
              <span class="currency">¥</span>
              <span class="amount">{{ formatPrice(totalAmount) }}</span>
            </span>
          </div>
        </div>
      </template>

      <!-- 空购物车状态 -->
      <a-empty v-else class="empty-cart" description="购物车是空的">
        <template #extra>
          <a-button type="primary" @click="goShopping"> 去购物 </a-button>
        </template>
      </a-empty>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { Empty, message, Modal } from "ant-design-vue";
import { ShopOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import {
  getCartItemsByStoreUsingGet,
  removeFromCartUsingPost,
  updateQuantityUsingPost,
  updateSelectedUsingPost,
} from "@/api/shoppingCartController";
import { createOrderFromCartUsingPost } from "@/api/orderController";
import type { CheckboxChangeEvent } from "ant-design-vue";

// 类型定义
interface CartItem {
  id: number;
  productId: number;
  productName: string;
  productImage: string;
  price: number;
  size: string;
  quantity: number;
  selected: number;
  storeId: number;
  totalPrice: number;
}

interface StoreCartGroup {
  storeId: number;
  storeName: string;
  cartItems: CartItem[];
}

// 状态管理
const router = useRouter();
const storeGroups = ref<StoreCartGroup[]>([]);
const defaultImage = "https://via.placeholder.com/200x200?text=No+Image";

// 获取购物车数据
async function fetchCartData() {
  try {
    const response = await getCartItemsByStoreUsingGet();
    if (response?.data?.code === 0 && response?.data?.data) {
      // 确保数据符合我们的类型定义
      storeGroups.value = response.data.data.map((store) => ({
        storeId: Number(store.storeId),
        storeName: store.storeName || "",
        cartItems: (store.cartItems || []).map((item) => ({
          id: Number(item.id),
          productId: Number(item.productId),
          productName: item.productName || "",
          productImage: item.productImage || "",
          price: Number(item.price) || 0,
          size: item.size || "",
          quantity: Number(item.quantity) || 1,
          selected: Number(item.selected) || 0,
          storeId: Number(item.storeId),
          totalPrice: Number(item.totalPrice) || 0,
        })),
      }));
    } else {
      message.error("获取购物车数据失败");
    }
  } catch (error) {
    message.error("获取购物车数据失败");
    console.error("获取购物车数据错误:", error);
  }
}

// 商店选择相关方法
function isStoreSelected(storeId: number): boolean {
  const store = storeGroups.value.find((s) => s.storeId === storeId);
  return store?.cartItems.every((item) => item.selected === 1) ?? false;
}

async function toggleStoreSelection(storeId: number, checked: boolean) {
  const store = storeGroups.value.find((s) => s.storeId === storeId);
  if (store) {
    for (const item of store.cartItems) {
      await updateSelectedUsingPost({
        id: item.id,
        productId: item.productId,
        quantity: item.quantity,
        selected: checked ? 1 : 0,
        size: item.size,
        storeId: item.storeId,
      });
    }
    await fetchCartData();
  }
}

// 商品操作方法
async function handleItemSelection(item: CartItem, checked: boolean) {
  try {
    await updateSelectedUsingPost({
      id: item.id,
      productId: item.productId,
      quantity: item.quantity,
      selected: checked ? 1 : 0,
      size: item.size,
      storeId: item.storeId,
    });
    await fetchCartData();
  } catch (error) {
    message.error("更新选择状态失败");
  }
}

async function handleQuantityChange(item: CartItem, value: number) {
  if (!value || value < 1) return;
  try {
    await updateQuantityUsingPost({
      id: item.id,
      productId: item.productId,
      quantity: value,
      selected: item.selected,
      size: item.size,
      storeId: item.storeId,
    });
    await fetchCartData();
  } catch (error) {
    message.error("更新数量失败");
  }
}

async function handleRemoveItem(item: CartItem) {
  try {
    await removeFromCartUsingPost({
      id: item.id,
      productId: item.productId,
      quantity: item.quantity,
      selected: item.selected,
      size: item.size,
      storeId: item.storeId,
    });
    message.success("商品已删除");
    await fetchCartData();
  } catch (error) {
    message.error("删除失败");
  }
}

// 结算相关方法
async function handleCheckout(store: StoreCartGroup) {
  const selectedItems = store.cartItems.filter((item) => item.selected === 1);
  if (selectedItems.length === 0) {
    message.warning("请选择要结算的商品");
    return;
  }

  try {
    const orderRequest = {
      items: selectedItems.map((item) => ({
        cartId: item.id,
        quantity: item.quantity,
      })),
    };
    const response = await createOrderFromCartUsingPost(orderRequest);
    if (response?.data?.code === 0) {
      message.success("创建订单成功");
      router.push(`/order/${response.data.data}`);
    }
  } catch (error) {
    message.error("创建订单失败");
  }
}

// 计算属性
const totalItems = computed(() => {
  return storeGroups.value.reduce(
    (total, store) => total + store.cartItems.length,
    0
  );
});

const totalSelectedItems = computed(() => {
  return storeGroups.value.reduce(
    (total, store) =>
      total + store.cartItems.filter((item) => item.selected === 1).length,
    0
  );
});

function calculateStoreTotal(store: StoreCartGroup): number {
  return store.cartItems
    .filter((item) => item.selected === 1)
    .reduce((total, item) => total + item.price * item.quantity, 0);
}

const totalAmount = computed(() => {
  return storeGroups.value.reduce(
    (total, store) => total + calculateStoreTotal(store),
    0
  );
});

// 工具函数
function formatPrice(price: number) {
  return price.toFixed(2);
}

function getStoreSelectedCount(store: StoreCartGroup) {
  return store.cartItems.filter((item) => item.selected === 1).length;
}

function hasStoreSelectedItems(store: StoreCartGroup): boolean {
  return store.cartItems.some((item) => item.selected === 1);
}

// 修改确认删除对话框中的类型
function confirmDelete(item: CartItem) {
  Modal.confirm({
    title: "确认删除",
    content: "确定要将这个商品从购物车中删除吗？",
    okText: "确认",
    cancelText: "取消",
    async onOk() {
      await handleRemoveItem(item);
    },
  });
}

// 跳转到商城
function goShopping() {
  router.push("/products");
}

// 生命周期钩子
onMounted(() => {
  fetchCartData();
});
</script>

<style scoped lang="scss">
.cart-container {
  @apply max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8;

  .cart-header {
    @apply flex justify-between items-center mb-6;
  }

  .store-group-card {
    @apply bg-white rounded-lg shadow-sm transition-shadow duration-300;

    &:hover {
      @apply shadow-md;
    }
  }

  .store-header {
    @apply flex justify-between items-center p-4 border-b border-gray-100;

    .store-name {
      @apply text-lg font-medium;
    }
  }

  .cart-items {
    @apply divide-y divide-gray-100;

    .cart-item {
      @apply flex items-center py-6 px-4 transition-colors duration-200;

      &:hover {
        @apply bg-gray-50;
      }
    }
  }

  .item-info {
    @apply flex flex-1 ml-4;

    .item-image-container {
      @apply w-24 h-24 flex-shrink-0 overflow-hidden rounded-md border border-gray-200;

      .item-image {
        @apply h-full w-full object-cover object-center;
      }
    }

    .item-details {
      @apply ml-4 flex flex-col justify-between;

      .item-name {
        @apply text-base font-medium text-gray-900;
      }

      .item-specs {
        @apply mt-1;
      }

      .item-price {
        @apply mt-1 text-sm text-gray-500;

        .currency {
          @apply text-xs;
        }

        .amount {
          @apply text-base font-medium;
        }
      }
    }
  }

  .item-actions {
    @apply flex items-center space-x-6;

    .quantity-control {
      @apply w-24;
    }

    .item-subtotal {
      @apply text-right min-w-[100px];

      .currency {
        @apply text-sm text-gray-500;
      }

      .amount {
        @apply text-lg font-medium text-primary;
      }
    }
  }

  .store-footer {
    @apply flex justify-between items-center p-4 bg-gray-50 rounded-b-lg;

    .checkout-area {
      @apply flex items-center space-x-4;

      .subtotal {
        @apply text-lg;

        .amount {
          @apply text-primary font-medium;
        }
      }
    }
  }

  .cart-summary {
    @apply fixed bottom-0 left-0 right-0 bg-white shadow-upper p-4 z-10;

    .summary-info {
      @apply flex justify-end items-center max-w-7xl mx-auto;

      .total-price {
        @apply text-primary text-xl font-medium ml-2;
      }
    }
  }

  .empty-cart {
    @apply py-16;
  }
}

// 动画效果
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

// 自定义主题色
:deep(.ant-btn-primary) {
  @apply bg-primary border-primary;

  &:hover {
    @apply bg-primary-dark border-primary-dark;
  }
}
</style>
